package reviewAlgorithms.greedyThought;

public class MaxProfit2 {

    public static void main(String[] args) {
        int[] prices = {2,1,2,0,1};
        System.out.println(maxProfit(prices));
    }

    public static int maxProfit(int[] prices) {
        if (prices == null || prices.length < 1){
            return 0;
        }
        int max = 0;
        int maxTemp = 0;
        int soFarMin = prices[0];
        for (int i = 0; i < prices.length; i++) {
            if (i - 1 >= 0 && prices[i] < prices[i - 1]) {
                soFarMin = prices[i];
                max += maxTemp;
                maxTemp = 0;
            }

            if (soFarMin > prices[i]){
                soFarMin = prices[i];
            }else {
                maxTemp = Math.max(maxTemp,prices[i] - soFarMin);

            }
        }

        return max;
    }

}
